package com.adtech.adms.system.web.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.adtech.adms.Constants;
import com.adtech.adms.SessionKey;
import com.adtech.adms.commons.web.action.DataGridAction;
import com.adtech.adms.system.SystemConstants;
import com.adtech.adms.system.SystemConstants.Department;
import com.adtech.adms.system.SystemConstants.Post;
import com.adtech.adms.system.pojo.Role;
import com.adtech.adms.system.pojo.Topo;
import com.adtech.adms.system.pojo.User;
import com.adtech.adms.system.service.RoleService;
import com.adtech.adms.system.service.TopoService;
import com.adtech.adms.system.service.UserService;
import com.adtech.core.dao.query.FilterItem;
import com.adtech.core.dao.query.FilterMap;
import com.adtech.core.dao.query.Pager;
import com.adtech.core.dao.query.Sort;
import com.adtech.core.dao.query.FilterItem.Formatters;
import com.adtech.core.dao.query.FilterItem.QueryType;
import com.adtech.core.exception.ServiceException;
import com.adtech.core.web.action.AjaxResult;

/**
 * 用户action
 * 用户action处理
 * @author Dormin 
 * @since 2011-8-11 
 * 
 * @Copyright (C) AD Tech Workshop All Right Reserved
 */
public class UserAction extends DataGridAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4775177870632543932L;

	private static final Logger log = Logger.getLogger(UserAction.class);

	private String id;
	private User user;
	private List<Post> posts;
	private String password;
	private String newPassword;
	private Integer loginUserId;

	private UserService userService;
	private TopoService topoService;
	private RoleService roleService;



	public List<LoginType> getLoginTypes() {
		List<LoginType> loginTypes=new ArrayList<LoginType>();
		loginTypes.add(new LoginType(User.TYPE_SYSTEM, Constants.LOGIN_TYPE_SYSTEM));
		loginTypes.add(new LoginType(User.TYPE_EIP, Constants.LOGIN_TYPE_EIP));
		loginTypes.add(new LoginType(User.TYPE_VPN, Constants.LOGIN_TYPE_VPN));
		return loginTypes;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}


	@Override
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserService getUserService() {
		return userService;
	}

	public TopoService getTopoService() {
		return topoService;
	}

	public void setTopoService(TopoService topoService) {
		this.topoService = topoService;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public Integer getLoginUserId() {
		return loginUserId;
	}

	public void setLoginUserId(Integer loginUserId) {
		this.loginUserId = loginUserId;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public String save() {
		
		obtainRoles();
		obtainTopos();
		try {
			User currentUser = (User) session.get(SessionKey.SESSION_KEY_USER);
			userService.save(user,currentUser);
			//User loginUser = (User) session.get(SessionKey.SESSION_KEY_USER);
			//loginUserId = loginUser.getUserId();
			setAjaxResult(AjaxResult.success());
//			addActionError("server error server error server error server error");
		} catch (ServiceException e) {
			setAjaxResult(AjaxResult.failed(e.getErrorCode(), e.getErrorMessage()));
		}
		return SUCCESS;
	}

	private void obtainRoles() {
		if (user.getRoleIds() != null && user.getRoleIds().length() != 0) {
			String[] ids = user.getRoleIds().split(",");
			List roles = new ArrayList<Role>();
			for (int i = 0; i < ids.length; i++) {
				if (!ids[i].equals("")) {
					Role role = roleService.getRoleById(new Long(ids[i]));
					roles.add(role);
				}
			}
			user.setRoles(roles);
		}
	}
	private void obtainTopos() {
		if (user.getTopoIds() != null && user.getTopoIds().length() != 0) {
			String[] ids = user.getTopoIds().split(",");
			List topos = new ArrayList<Topo>();
			for (int i = 0; i < ids.length; i++) {
				if (!ids[i].equals("")) {
					Topo topo = topoService.getTopoById(new Long(ids[i]));
					topos.add(topo);
				}
			}
			user.setTopos(topos);
		}
	}

	public String getDetail() {
		if (id != null) {
			user = userService.getUser(new Integer(id));

		}
		return SUCCESS;
	}

	public String delete() {
		if (id != null && id.length() > 0) {
			try {
				User currentUser = (User) session.get(SessionKey.SESSION_KEY_USER);
				userService.delete(id,currentUser);
				setAjaxResult(AjaxResult.success());
			} catch (ServiceException e) {
				log.error(e);
				setAjaxResult(AjaxResult.failed(e.getErrorCode(), e.getErrorMessage()));
			}
		}
		return SUCCESS;
	}

	public String getCheck() {
		if(id!=null && id.length()>0){
			user.setUserId(new Integer(id));
		}
		try {
			userService.check(user);
			setAjaxResult(AjaxResult.success());
		} catch (ServiceException e) {
			setAjaxResult(AjaxResult.failed(e.getErrorCode(), e.getErrorMessage()));
		}
		return SUCCESS;
	}
	


	@Override
	protected List getModelDataGridList(Pager pager, FilterMap filtermap, Sort sort) {
		addUserCompanyCondition(filtermap);
		return userService.getUserList(pager, filtermap.toExpression(), sort);

	}

	/**
	 * 
	 * @function 限制登录用户访问用户列表，当前用户只能查看所属单位以及以下单位的用户
	 * @param
	 *
	 * @return
	 * @exception
	 *
	 * @author Dormin
	 * @history
	 *
	 */
	private void addUserCompanyCondition(FilterMap filtermap) {
		User user = (User) session.get(SessionKey.SESSION_KEY_USER);
		FilterItem fullPathIdsItem = new FilterItem();
		fullPathIdsItem.setExpType(QueryType.LIKE.name());
		fullPathIdsItem.setFilterName(SystemConstants.User.FULLPATHIDS);
		fullPathIdsItem.setFormatter(Formatters.LikeFormatter.name());

		FilterItem idItem = new FilterItem();
		idItem.setExpType(QueryType.EQ.name());
		idItem.setFilterName(SystemConstants.User.COMPANY_ID);
//		idItem.setFilterValue(Long.toString(user.getDepartment().getCompany().getId()));

		String linkOperate  = "("+SystemConstants.User.FULLPATHIDS+"|"+SystemConstants.User.COMPANY+")";

		for(FilterItem item:filtermap.values()){
			if(item.getFilterValue()!=null){
				String value = item.getFilterValue().toString();
				if(value!=null && value.length()>0){
					linkOperate = item.getFilterName() + "&" + linkOperate;
				}
			}
		}

		filtermap.put(SystemConstants.User.FULLPATHIDS, fullPathIdsItem);
		filtermap.put(SystemConstants.User.COMPANY, idItem);
		filtermap.setLinkOperate(linkOperate);
	}

	public List<Post> getPosts() {
		return posts;
	}

	public void setPosts(List<Post> posts) {
		this.posts = posts;
	}



	public class LoginType {

		public LoginType(byte value, String name) {
			this.value = value;
			this.name = name;
		}

		public byte getValue() {
			return value;
		}

		public void setValue(byte value) {
			this.value = value;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		byte value;
		String name;
	}



	/**
	 * 
	 * @function 进入列表页面
	 * @param
	 *
	 * @return
	 * @exception
	 *
	 * @author Dormin
	 * @history
	 *
	 */
	public String main(){
//		User loginUser = (User) session.get(SessionKey.SESSION_KEY_USER);
//		loginUserId = loginUser.getUserId();
		return SUCCESS;
	}

	/**
	 * 管理员批量重置用户密码
	 * @throws ServiceException 
	 *
	 * @author Dormin
	 */
	public String resetPassword() throws ServiceException{
		password = userService.resetPassword(id);
		setAjaxResult(AjaxResult.success(null,password));
		return SUCCESS;
	}

	/**
	 * 
	 * @function 当前登录用户进入修改密码页面
	 * @param
	 *
	 * @return
	 * @exception
	 *
	 * @author Dormin
	 * @history
	 *
	 */
	public String changePassword(){
		user = (User) session.get(SessionKey.SESSION_KEY_USER);
		try {
			userService.changePassword(user, password, newPassword, null);
			setAjaxResult(AjaxResult.success());
		} catch (ServiceException e) {
			setAjaxResult(AjaxResult.failed(e.getErrorCode(), e.getErrorMessage()));
		}
		return SUCCESS;
	}
	/**
	 * 
	 * @function 用户修改自己密码
	 * @param
	 *
	 * @return
	 * @exception
	 *
	 * @author Dormin
	 * @history
	 *
	 */
//	public String savePassword(){
//		try {
//			User currentUser = (User) session.get(SessionKey.SESSION_KEY_USER);
//			userService.changePassword(user, password, newPassword,currentUser);
//			setAjaxResult(AjaxResult.success());
//		} catch (ServiceException e) {
//			log.error(e);
//			setAjaxResult(AjaxResult.failed(e.getErrorCode(), e.getErrorMessage()));
//		}
//		return SUCCESS;
//	}

	/**
	 * 
	 * @function 检查密码
	 * @param
	 *
	 * @return
	 * @exception
	 *
	 * @author
	 * @history
	 *
	 */
	public String checkPassword(){
		try {
			user = (User) session.get(SessionKey.SESSION_KEY_USER);
			userService.checkPassword(user.getUserId(), password);
			setAjaxResult(AjaxResult.success());
		} catch (ServiceException e) {
			log.error(e);
			setAjaxResult(AjaxResult.failed(e.getErrorCode(), ""));
		}
		return SUCCESS;
	}

    


}
